/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { debounce, isEmpty } from 'lodash';
import {
  Modal,
  Divider,
  Card,
  Row,
  Col,
  Form,
  Select,
  Input,
  Button,
  DatePicker,
  Spin,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import DownloadBar from '@/components/DownloadBar';
import InfoCheck from '@/components/InfoCheck';
import canvasDraw from '../../utils/canvasDraw';
import styles from './style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
@connect(({ loading, order, station, user }) => ({
  station,
  order,
  user,
  // operatoring: loading.effects['operator/getOperatorList'],
  stationing: loading.effects['station/getStationList'],
  loading: loading.effects['order/getOrderList'],
  operatoring: loading.effects['order/siteOperator'],
}))
@Form.create()
export default class Order extends PureComponent {
  state = {
    currentStation: null,
    stationList: [],
  };

  handleSearch = debounce(e => {
    e.preventDefault();
    const { dispatch, station: { company_info } } = this.props;
    this.getFormValues(values => {
      const site_code = values.site_code == company_info?.brand_code ? 999 : values.site_code
      dispatch({
        type: 'order/getOrderList',
        payload: {
          ...values,
          site_code,
        },
      });
    });
  }, 500, {
    leading: true,
    trailing: false,
  });

  handleStandardTableChange = debounce(pagination => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
    };
    dispatch({
      type: 'order/getOrderList',
      payload: params,
    });
  }, 500, {
    leading: true,
    trailing: false,
  });

  onGetOperatorList = () => {
    const { dispatch, station } = this.props;
    const { company_info } = station
    const { currentStation } = this.state;
    const { code } = currentStation || { code: '' };
    const site_code = code == company_info?.brand_code ? 999 : code;
    dispatch({
      type: 'order/siteOperator',
      payload: {
        site_code,
      },
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children, value } = options.props;
    if (children.indexOf(inputValue) >= 0 || value.toString().indexOf(inputValue) >= 0) return true;
  };

  onScrollOperator = () => {};

  onSelectStation = code => {
    if (!code) return;
    const { currentStation } = this.state;
    if (currentStation && currentStation.code == code) return;
    this.setState({
      currentStation: {
        code,
      },
    });
    const { form } = this.props;
    form.setFieldsValue({
      courier_no: '0',
    });
  };

  onGetStationList = () => {
    const { dispatch, station } = this.props;
    dispatch({
      type: 'station/getStationList',
    }).then(() => {
      const { list = [], company_info = {} } = station
      const stationList = list || []

      if (!isEmpty(company_info)) {
        stationList.unshift({
          site_code: company_info.brand_code,
          site_name: company_info.brand_name,
        });
      }
      this.setState({
        stationList,
      })
    });
  };

  handleInfoReady = data => {
    if (!data.name) return;
    const { dispatch } = this.props;
    dispatch({
      type: 'order/getOrderList',
      payload: {},
    });
    this.onGetStationList()
  };

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_at = start;
        values.end_at = end;
        delete values.date;
      }
      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  handlePreviewImage = (flag, currentData) => {
    this.setState({
      showImage: flag,
    });
    setTimeout(() => {
      if (currentData) {
        const oCanvas = document.getElementById('canvas');
        const cs = canvasDraw.init(oCanvas);
        const drawConfig = {
          brand: '',
          area: '',
          waybill_number: currentData.waybill_no,
          r_info: {
            name: currentData.recipient_name,
            phone: `${currentData.recipient_mobile} ${
              currentData.recipient_tel ? currentData.recipient_tel : ''
            }`,
            province: currentData.recipient_province,
            city: currentData.recipient_city,
            area: currentData.recipient_district,
            address: `${currentData.recipient_province}${currentData.recipient_city}${
              currentData.recipient_district
            }${currentData.recipient_address}`,
          },
          s_info: {
            name: currentData.sender_name,
            phone: `${currentData.sender_mobile} ${
              currentData.sender_tel ? currentData.sender_tel : ''
            }`,
            province: currentData.sender_province,
            city: currentData.sender_city,
            area: currentData.sender_district,
            address: `${currentData.sender_province}${currentData.sender_city}${
              currentData.sender_district
            }${currentData.sender_address}`,
          },
        };
        cs.drawStart(drawConfig);
      }
    }, 100);
  };

  downloadData = () => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const { site_code, courier_no, waybill_no, date } = getFieldsValue();
    const data = {
      d_l: 1,
      courier_no,
      waybill_no,
      site_code,
      start_at: moment(date[0]).format(dateFormat),
      end_at: moment(date[1]).format(dateFormat),
    };
    return { ...data };
  };

  render() {
    const { showImage, stationList } = this.state;
    const { order, loading, form, stationing = false, operatoring = false } = this.props;
    const { getFieldDecorator } = form;
    const { list, pagination } = order;
    const data = { list, pagination };
    const operatorList = order.data;
    const columns = [
      {
        title: '单号',
        dataIndex: 'waybill_no',
      },
      {
        title: '电子面单',
        dataIndex: 'order',
        render: (current, currentData) => {
          const { created_at, remark } = currentData;
          return (
            <Fragment>
              <Row>
                发件：
                {[
                  currentData.sender_name,
                  `${currentData.sender_mobile} ${
                    currentData.recipient_tel ? currentData.recipient_tel : ''
                  }`,
                  currentData.sender_province +
                    currentData.sender_city +
                    currentData.sender_district +
                    currentData.sender_address,
                ].join('，')}
              </Row>
              <Row>
                收件：
                {[
                  currentData.recipient_name,
                  `${currentData.recipient_mobile} ${
                    currentData.sender_tel ? currentData.sender_tel : ''
                  }`,
                  currentData.recipient_province +
                    currentData.recipient_city +
                    currentData.recipient_district +
                    currentData.recipient_address,
                ].join('，')}
              </Row>
              <Row>
                <span>
                  物品：
                  {currentData.trade_name}
                </span>
                <Divider type="vertical" />
                <span>
                  重量：
                  {currentData.weight}
                  kg
                </span>
              </Row>
              <Row>
                {remark && (
                  <Fragment>
                    <span>{`备注：${remark}`}</span>
                  </Fragment>
                )}
              </Row>
              <Row>
                订单创建时间：
                {created_at}
              </Row>
            </Fragment>
          );
        },
      },
      {
        title: '公司站点',
        dataIndex: 'station',
      },
      {
        title: '业务员',
        render: (current, currentData) => {
          if (currentData.courier_name) {
            if (currentData.job_number) {
              return `${currentData.courier_name}-${currentData.job_number}`;
            }
              return `${currentData.courier_name}`;
          } if (currentData.job_number) {
            return `${currentData.job_number}`;
          }
            return '--';
        },
        dataIndex: 'operator',
      },
      {
        title: '扫描状态',
        dataIndex: 'order_status',
      },
      {
        title: '底单',
        render: (current, currentData) => (
            <Button
              ghost
              onClick={() => this.handlePreviewImage(true, currentData)}
              type="primary"
              size="small"
            >
              查看底单
            </Button>
          ),
        dataIndex: 'certificatPath',
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    // 默认选择时间
    const defaultSelectDate = {
      startDate: moment()
        .startOf('day')
        .subtract(31, 'days'),
      endDate: moment().endOf('day'),
    };
    return (
      <PageHeaderLayout title="同城订单">
        <div className={styles.main}>
          <Card bordered={false} bodyStyle={{ padding: '0 0 24px' }}>
            <Form onSubmit={this.handleSearch} className={styles['search-form']}>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={9} sm={24}>
                  <FormItem {...formItemLayout} label="订单创建时间">
                    {getFieldDecorator('date', {
                      initialValue: [defaultSelectDate.startDate, defaultSelectDate.endDate],
                    })(
                      <RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始日期', '结束日期']}
                      />,
                    )}
                  </FormItem>
                </Col>
                <Col md={9} sm={24}>
                  <FormItem label="公司站点" {...formItemLayout}>
                    {getFieldDecorator('site_code')(
                      <Select
                        onFocus={this.onGetStationList}
                        onSelect={this.onSelectStation}
                        placeholder="请选择公司站点"
                        allowClear
                      >
                        {stationing ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="0">
                            全部站点
                          </Option>
                        )}
                        {stationList.map(({ site_code, site_name }) => (
                          <Option key={site_code} value={site_code}>
                            {site_name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={9} sm={24}>
                  <FormItem {...formItemLayout} label="业务员">
                    {getFieldDecorator('courier_no')(
                      <Select
                        onFocus={this.onGetOperatorList}
                        filterOption={this.onFilterOperator}
                        onPopupScroll={this.onScrollOperator}
                        showSearch
                        allowClear
                        placeholder="请输入姓名或者工号"
                      >
                        {operatoring ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="0">
                            全部业务员
                          </Option>
                        )}
                        {operatorList.map(({ courier_no, courier_name }) => (
                          <Option key={courier_no} value={courier_no}>
                            {courier_name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={9} sm={24}>
                  <FormItem {...formItemLayout} label="同城单号" validateStatus="success">
                    {getFieldDecorator('waybill_no')(<Input placeholder="请输入同城单号" />)}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <span className={styles.submitButtons}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      key="search"
                      icon="search"
                      loading={loading}
                    >
                      查询
                    </Button>
                  </span>
                </Col>
              </Row>
            </Form>
          </Card>
          <div style={{ paddingBottom: '24px' }}>
            <DownloadBar href="/Api/Order/index" query={this.downloadData}>
              <Button type="primary" icon="download">
                导出
              </Button>
            </DownloadBar>
          </div>
          <StandardTable
            rowKey="id"
            loading={loading}
            data={data}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
        <Modal
          wrapClassName="preview-image-modal"
          centered
          onCancel={() => this.handlePreviewImage(false)}
          footer={null}
          visible={showImage}
          destroyOnClose
        >
          <div style={{ padding: '10px', background: '#fff' }}>
            <canvas id="canvas" width="410" height="474" />
          </div>
        </Modal>
        <canvas id="canvasBar" style={{ display: 'none' }} />
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
      </PageHeaderLayout>
    );
  }
}
